<template>
  <div class="forgot-container">
    <el-card class="forgot-card">
      <el-steps :active="step" align-center class="steps">
        <el-step title="身份验证" />
        <el-step title="重置密码" />
      </el-steps>

      <!-- 步骤1：账号验证 -->
      <transition name="el-fade-in" mode="out-in">
        <div v-if="step === 1" key="step1" class="step-box">
          <h2 class="title">🔐 身份验证</h2>
          <el-form
              ref="verifyFormRef"
              :model="verifyForm"
              :rules="rules"
              @submit.native.prevent="handleVerify"
              class="verify-form"
          >
            <el-form-item prop="username">
              <el-input
                  v-model="verifyForm.username"
                  placeholder="请输入需要重置的账号"
                  clearable
                  size="large"
                  :prefix-icon="User"
              >
                <template #prepend>
                  <span class="input-prepend">账号</span>
                </template>
              </el-input>
            </el-form-item>

            <el-button
                type="primary"
                native-type="submit"
                :loading="verifying"
                size="large"
                class="submit-btn"
            >
              {{ verifying ? '验证中...' : '下一步' }}
              <el-icon class="el-icon--right"><ArrowRight /></el-icon>
            </el-button>
          </el-form>
        </div>
      </transition>

      <!-- 步骤2：密码重置 -->
      <transition name="el-fade-in" mode="out-in">
        <div v-if="step === 2" key="step2" class="step-box">
          <h2 class="title">🔄 重置密码</h2>
          <el-form
              ref="resetFormRef"
              :model="resetForm"
              :rules="rules"
              @submit.native.prevent="handleReset"
              class="reset-form"
          >
            <el-form-item prop="newPassword">
              <el-input
                  v-model="resetForm.newPassword"
                  type="password"
                  placeholder="至少8位且包含字母数字"
                  show-password
                  size="large"
                  :prefix-icon="Lock"
              >
                <template #prepend>
                  <span class="input-prepend">新密码</span>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                  v-model="resetForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
                  show-password
                  size="large"
                  :prefix-icon="Lock"
              >
                <template #prepend>
                  <span class="input-prepend">确认密码</span>
                </template>
              </el-input>
            </el-form-item>

            <el-button
                type="success"
                native-type="submit"
                :loading="resetting"
                size="large"
                class="submit-btn"
            >
              {{ resetting ? '提交中...' : '确认重置' }}
              <el-icon class="el-icon--right"><Check /></el-icon>
            </el-button>
          </el-form>
        </div>
      </transition>

      <div class="back-login">
        <el-link type="info" @click="goToLogin">
          <el-icon><ArrowLeft /></el-icon>
          返回登录
        </el-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import router from '../router/index.js'
import { User, Lock, ArrowRight, Check, ArrowLeft } from '@element-plus/icons-vue'
import { verifyAccount, resetPassword } from '../service/userApi.js'

// 表单校验规则
const rules = reactive({
  username: [
    { required: true, message: '账号不能为空', trigger: ['blur', 'change'] }
  ],
  newPassword: [
    { required: true, message: '密码不能为空', trigger: ['blur', 'change'] },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d).{6,}$/,
      message: '需至少6位且包含字母数字',
      trigger: ['blur', 'change']
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: ['blur', 'change'] },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ]
})

// 响应式数据
const step = ref(1)
const verifying = ref(false)
const resetting = ref(false)
const verifyToken = ref('')
const verifyFormRef = ref()
const resetFormRef = ref()

const verifyForm = reactive({
  username: ''
})

const resetForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 处理方法
const handleVerify = async () => {
  try {
    await verifyFormRef.value.validate()
    verifying.value = true
    const res = await verifyAccount({ username: verifyForm.username })
    verifyToken.value = res.data
    step.value = 2
    ElMessage.success('验证通过，请设置新密码')
  } finally {
    verifying.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}

const handleReset = async () => {
  try {
    await resetFormRef.value.validate()
    resetting.value = true
    const params = {
      username: verifyForm.username,
      verifyToken: verifyToken.value,
      newPassword: resetForm.newPassword
    }
    const result = await resetPassword(params)
    if (result.code === 200) {
      ElMessage.success('密码重置成功，请重新登录')
      goToLogin()
    }
  } catch (e) {
    if (e?.message) {
      ElMessage.error(e.message)
    } else {
      ElMessage.error(e.response?.data?.message || '重置失败')
    }
  } finally {
    resetting.value = false
  }
}
</script>

<style scoped>
.forgot-container {
  max-width: 500px;
  margin: 40px auto;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.step-box {
  transition: all 0.3s ease;
}

h2 {
  margin-bottom: 25px;
  text-align: center;
  color: #303133;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-button {
  width: 100%;
  margin-top: 15px;
}
</style>